
package com.tspp.common;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Locale;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;

/**
 * Manage the connection pool of tomcat server in this application
 * @author Maks
 */
public class ResourceManager {

    private static DataSource dataSource;

    /**
     * retriev the connection from connection pool
     * @return database connection
     * @throws NamingException
     * @throws SQLException
     */
    public static synchronized Connection getConnection() throws NamingException, SQLException {
        if (dataSource == null) {
            Locale.setDefault(Locale.ENGLISH);
            Context context = (Context) new InitialContext().lookup("java:comp/env");
            dataSource = (DataSource) context.lookup("jdbc/ARM");
            context.close();
        }
        return dataSource.getConnection();
    }

    /**
     * Utility method. Close connection
     * @param con connection to close
     */
    public static void close(Connection con) {
        if (con != null)
            try {
            con.close();
        } catch (SQLException ex) {
            Logger.getLogger(ResourceManager.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /**
     * Utility method. Close Resultset
     * @param rs resultset to close
     */
    public static void close(ResultSet rs) {
        if (rs != null)
            try {
            rs.close();
        } catch (SQLException ex) {
            Logger.getLogger(ResourceManager.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /**
     * Utility method. Close PreparedStatement
     * @param stmt preparedStatement to close
     */
    public static void close(PreparedStatement stmt) {
        if (stmt != null)
            try {
            stmt.close();
        } catch (SQLException ex) {
            Logger.getLogger(ResourceManager.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}
